package com.ljw.spring.annotation.tx;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @FileName ConfigOfTx
 * @Description TODO 事务
 * 环境搭建：
 * 1. 依赖： 数据源、数据库驱动、spring-jdbc模块
 * 2. 配置数据源、JdbcTemplate(spring-jdbc提供的简化操作数据库的工具)
 * 3. 给业务方法标注注解@Transactional：表示该方法是一个事务方法
 * 4. @EnableTransactionManagement:开启基于注解的事务管理功能
 * 5. 将事务管理器注册进入IOC容器
 *      @Bean
        public TransactionManager getTransactionManager(DataSource dataSource){}
 * @Author ljw
 * @Date 2021/2/4 0:15
 * @Version 1.0
 */
@EnableTransactionManagement
@PropertySource(value = {"classpath:/db.properties"})
@Configuration
@ComponentScan(basePackages = {"com.ljw.spring.annotation.tx"})
public class ConfigOfTx {

    @Value("${db.user}")
    private String user;

    @Value("${db.driverClass}")
    private String driverClass;

    @Bean(value = {"dataSource"})
    public DataSource getDataSource(@Value("${db.password}")String password) throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setUser(user);
        dataSource.setPassword(password);
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
        dataSource.setDriverClass(driverClass);
        return dataSource;
    }

    //用@Bean向容器添加组件时，方法参数组件是自动从IOC容器中获取对应的实例对象。@Autowired写不写都可以
    @Bean
    public JdbcTemplate getJdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }


    @Bean
    public TransactionManager getTransactionManager(DataSource dataSource){
        //事务管理器
        return new DataSourceTransactionManager(dataSource);
    }
}
